package com.daniel.memo;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.daniel.database.*;


public class MainActivity extends ListActivity {
	
	public static final boolean DEBUG_ON = true;
	
	private ItemAdapter memoAdapter;
	private List<Memo> memoList;
	
//	private Button addBtn;
	private Button deleteBtn;
	private Button cancelBtn;
	
	private Dialog addItemDialog;
	private Dialog addTodoDialog;
	private Dialog editTodoDialog;	
	
	private Button addMemoBtn;
	private Button addTodoBtn;
	
	private Button editMemoBtn;
	private EditText editTile;
	private TextView editTodoMemoId;
	
	private EditText todoTitleTxtEdit;
	private Button createTodoBtn;
	
	private Database db;	
	
	private boolean isDeleteModeOn = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memo_list_view);
        connectInput();

        db = new Database(this);
        
        registerForContextMenu(getListView());
    }
    
    @Override
    public void onStart() {
    	super.onStart();
    	db.open();
    	initList();
    }
 
    @Override
    public void onStop() {
    	super.onStop();
    	db.close();
    }

    
    //short click
    @Override
    public void onListItemClick(ListView list, View v, int position, long id) {
    	super.onListItemClick(list, v, position, id);
    	Memo memo = (Memo) list.getItemAtPosition(position);
    	int memoType = memo.getType();
    	
    	switch (memoType) {
    		case Memo.MEMO_TYPE:
    			runViewMemoActivityWithMemoId(memo.getMemoId());
    			return;
    			
    		case Memo.TODO_TYPE:
    			Todo todo = (Todo)memo;
    			runTodoViewActivity(todo.getTodoId());
    			return;
    			
    		default:
    	}
    }

    
    //Create Long press menu on the list
    @Override 
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	getMenuInflater().inflate(R.menu.list_menu_item_longpress, menu);
    }
    
    //if user select one of the items on long pressed menu 
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();      
    	List<Memo> tempMemoList = memoAdapter.getMemoList();

    	switch (item.getItemId()) {
    		case R.id.memu_delete_id:
    			int memoId = tempMemoList.get(info.position).getMemoId();
    			db.deleteByMemoId(memoId);
    			db.deleteTodoById(memoId);
    			initList();
    			return true;

    		case R.id.menu_edit_id:
    			int itemType = tempMemoList.get(info.position).getType();
    			
    			if (itemType == Memo.MEMO_TYPE) {
    				runEditMemoActivityWithMemoId(tempMemoList.get(info.position).getMemoId());
    			} else if (itemType == Memo.TODO_TYPE){
    				//create editTodo method
    				String todoTitle =  tempMemoList.get(info.position).getTitle();
    				int taskMemoId = tempMemoList.get(info.position).getMemoId();
    				initEditTodoDialog();
    				editTile.setText(todoTitle);
    				editTodoMemoId.setText("" + taskMemoId);
    				editTodoDialog.show();
    				
    			}
    			return true;
    	}
    	return true;
    }
    
    
    public void initEditTodoDialog() {
    	editTodoDialog = new Dialog(this);
    	editTodoDialog.setTitle(R.string.edit_todo_popup_title);
    	editTodoDialog.setContentView(R.layout.edit_todo_dialog);
    	
    	editTile = (EditText) editTodoDialog.findViewById(R.id.edit_todo_title_edtTxt_id);
    	editTodoMemoId = (TextView) editTodoDialog.findViewById(R.id.edit_todo_memoId_id);
    	
		editMemoBtn = (Button) editTodoDialog.findViewById(R.id.edit_todo_title_btn_id);
		editMemoBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				int memoId = Integer.parseInt(editTodoMemoId.getText().toString());
				db.updateTitle(memoId, editTile.getText().toString());
				editTodoDialog.dismiss();
				initList();
			}
		});
    }
    
    
    //Menu option
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	getMenuInflater().inflate(R.menu.list_view_option_menu , menu);
        return true;
    }

    //Select items on the Menu selection
    @Override 
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
    	switch(item.getItemId()) {
    		case R.id.list_view_menu_delete_cancel_id:    			
    			switchMode();

    			return true;    			
    		case R.id.list_view_menu_add_id:
    			initAddItemDialog();    			
    			addItemDialog.show();

    			return true;
    	}
    	return super.onMenuItemSelected(featureId, item);
    }
    
    
    //initialize item list
    public void initList() {
    	memoList = new ArrayList<Memo>();
    	Cursor itemCursor = db.fetchAllMemoForMain();
    	Memo tempMemo; 
    	Todo tempTodo;
    	
    	while (itemCursor.moveToNext()) {
    		int type = itemCursor.getInt(2);
    		if (type == Memo.MEMO_TYPE) {
    			tempMemo = new Memo(itemCursor.getInt(0),itemCursor.getString(1), type);
    			memoList.add(tempMemo);
    			
    		} else if (type == Memo.TODO_TYPE) {
    			int memoId = itemCursor.getInt(0);

    			Cursor todoCursor = db.fetchTodoByMemoId(memoId);
    			
    			todoCursor.moveToNext();
    			int todoId = todoCursor.getInt(0);

    			tempTodo = new Todo(memoId, itemCursor.getString(1), type, todoId);
    			memoList.add(tempTodo);
    		}
    	}
    	
    	memoAdapter = new ItemAdapter(this, R.layout.item_row, memoList);
    	setListAdapter(memoAdapter);
    }

    
    //Buttons
    private void connectInput() {
    	deleteBtn = (Button) findViewById(R.id.delete_item_btn_id);
    	deleteBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				int deleteSelectedItems = deleteSelectedItems();
				if (deleteSelectedItems <= 0) {
					Toast.makeText(getApplicationContext(), "Please select items you want to delete", Toast.LENGTH_SHORT).show();
				} else {
					switchMode();
					initList();
				}
			}
		});
    	
    	cancelBtn =(Button) findViewById(R.id.cancel_delete_item_btn_id);
    	cancelBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				switchMode();
				initList();				
			}
		});
    }


    //switch to delete or normal mode 
    public void switchMode() {
    	if (isDeleteModeOn == false) {
    		deleteBtn.setVisibility(View.VISIBLE);
    		cancelBtn.setVisibility(View.VISIBLE);
    		isDeleteModeOn = true;
    		initList();
    		
    	} else {
    		deleteBtn.setVisibility(View.GONE);
    		cancelBtn.setVisibility(View.GONE);
    		isDeleteModeOn = false;
    		initList();
    		
    	}
    }
    
    
    private class ItemAdapter extends ArrayAdapter<Memo> implements OnClickListener {
    	private List<Memo> memoList;
    	private Activity context;

		private TextView title;
		private TextView type;

		private CheckBox itemCheckbox;

        public ItemAdapter(Activity context, int resource, List<Memo> memoList) {
                super(context, R.layout.item_row, memoList);
                this.memoList = memoList;
                this.context = context;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        		View view = null;
                final Memo memo = memoList.get(position);
                
                if (convertView == null) {
                	LayoutInflater inflater = context.getLayoutInflater();
                	view = inflater.inflate(R.layout.item_row, null);
                	
                	title = (TextView) view.findViewById(R.id.title_row_txt_id);
                	title.setText(memo.getTitle());
                	
                	type = (TextView) view.findViewById(R.id.type_row_txt_id);
                	int itemType = memo.getType();
                	if (itemType == Memo.MEMO_TYPE) {
                		type.setText("" + Memo.MEMO_TYPE_STR);
                	} else if (itemType == Memo.TODO_TYPE) {
                		type.setText("" + Memo.TODO_TYPE_STR);
                	} else { // Task
                		type.setText("" + Memo.TASK_TYPE_STR);
                	}
                	
                	itemCheckbox = (CheckBox)view.findViewById(R.id.item_check_id);
	                if (isDeleteModeOn) {
	                	itemCheckbox.setVisibility(View.VISIBLE);
	                } else {
	                	itemCheckbox.setVisibility(View.INVISIBLE);
	                }
	                
	                itemCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							if (isChecked == true) { 
								memo.setIsSeleted(true);
							} else {
								memo.setIsSeleted(false);
							}							
						}
					});
                	
                } else {
                	view = convertView;
                }
                
                return view;
        }
        
        public List<Memo> getMemoList() {
        	return this.memoList;
        }
        
        public Memo getMemo(int index) {
        	return memoList.get(index);
        }
        
        public void onClick(View v) {
        }
    }

    
    public int deleteSelectedItems() {
    	List<Memo> tempMemoList = memoAdapter.getMemoList();
    	Iterator<Memo> itr = tempMemoList.iterator();
    	int deletedItemCount = 0;
    	while (itr.hasNext()) {
    		int rowId;
    		Memo tempMemo = (Memo)itr.next();
    		if (tempMemo.getIsSeleted() == true) {
    			rowId = tempMemo.getMemoId();
    			db.deleteByMemoId(rowId);
    			deletedItemCount++;
    		}
    	}
    	
    	return deletedItemCount;
    }
    
    
    public void initAddItemDialog(){
		addItemDialog = new Dialog(this); 
		addItemDialog.setTitle(R.string.add_item_popup_title);
		addItemDialog.setContentView(R.layout.add_item_dialog);
		
		addMemoBtn = (Button) addItemDialog.findViewById(R.id.add_memo_btn_id);
		addMemoBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				runEditMemoActivity();
				addItemDialog.dismiss();
			}
		});

		addTodoBtn = (Button) addItemDialog.findViewById(R.id.add_todo_btn_id);
		addTodoBtn.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				addItemDialog.dismiss();
				initAddTodoDialog();
				addTodoDialog.show();
			}
		});
    }

    public void initAddTodoDialog() {
    	addTodoDialog = new Dialog(this); 
    	addTodoDialog.setTitle(R.string.add_todo_popup_title);
    	addTodoDialog.setContentView(R.layout.add_todo_dialog);
    	
    	todoTitleTxtEdit = (EditText) addTodoDialog.findViewById(R.id.add_todo_item_edtTxt_id);
    	
    	createTodoBtn = (Button) addTodoDialog.findViewById(R.id.create_todo_item_btn_id);
    	createTodoBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Log.d("EditText", todoTitleTxtEdit.getText().toString());
				String todoTitle = todoTitleTxtEdit.getText().toString();
				
				if (!TextUtils.isEmpty(todoTitle)) {
					Todo todo = new Todo(todoTitle);

					memoList.add(todo);
					db.insertTodo(todo.getTitle());
					initList();
					addTodoDialog.dismiss();
					
				} else {
					Toast.makeText(getApplicationContext(), "Please enter the title", Toast.LENGTH_LONG).show();
					
				}
			}
		});
    }

    public void runEditMemoActivity() {
        Intent memoEditIntent = new Intent(this , MemoEditActivity.class);
        startActivity(memoEditIntent);    	
    }

    public void runEditMemoActivityWithMemoId(int memoid) {
        Intent memoEditIntent = new Intent(this , MemoEditActivity.class);
        memoEditIntent.putExtra(Memo.MEMO_ID,memoid);
        startActivity(memoEditIntent);    	    	
    }

    public void runViewMemoActivityWithMemoId(int memoid) {
        Intent viewEditIntent = new Intent(this , MemoViewActivity.class);
        viewEditIntent.putExtra(Memo.MEMO_ID, memoid);
        startActivity(viewEditIntent);    	    	
    }
    
    public void runTodoViewActivity(int todoid) {
        Intent todoViewIntent = new Intent(this , TodoViewActivity.class);
        todoViewIntent.putExtra(Todo.TODO_ID, todoid);
        startActivity(todoViewIntent);
    }
    
}

